package collect

import (
	"context"

	"mall/common/ctxdatax"
	"mall/common/enumx"
	"mall/common/mqueuex"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCollectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateCollectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCollectLogic {
	return &CreateCollectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateCollectLogic) CreateCollect(req *types.CreateCollectReq) (resp *types.CreateCollectResp, err error) {
	if req.PerfumeId == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	if req.PerfumeId > 0 {
		parent, err := l.svcCtx.BlogRpc.BookDetail(l.ctx, &blogclient.BookDetailReq{
			Id:        req.PerfumeId,
			Preload:   "blogBook:Id,Title,Slug;blogBookMeta:year,averageRating,minProductGems,popularity,season,gender",
			EagerLoad: "blogBook:blogBookMeta",
		})
		if err != nil {
			return nil, err
		}

		var meta []*forumclient.ForumMeta
		meta = append(meta, &forumclient.ForumMeta{
			Key:   "slug",
			Value: parent.Slug,
		})
		if len(parent.Meta) > 0 {
			for _, m := range parent.Meta {
				switch m.Key {
				case "year", "minProductGems", "averageRating", "popularity", "season", "gender":
					meta = append(meta, &forumclient.ForumMeta{
						Key:   m.Key,
						Value: m.Value,
					})
				}
			}
		}
		_, err = l.svcCtx.ForumRpc.CreateCollect(l.ctx, &forumclient.CreateCollectReq{
			ObjectId:   req.PerfumeId,
			ObjectType: int32(enumx.PostTypeKnowledgeBase),
			VisitorId:  int64(userId),
			PlatformId: int32(enumx.ThirdPartyPlatformWechatMini),
			Meta:       meta,
		})
		if err != nil {
			return nil, err
		}
	}

	var userMeta []*userclient.UserMetaInfo
	userMeta = append(userMeta, &userclient.UserMetaInfo{
		Key:   pointy.GetPointer(mqueuex.UserStatisticCollectEntryNew), // "_collect_entry_status"
		Value: pointy.GetPointer("-1"),
	})
	l.svcCtx.UserRpc.SetUserMeta(l.ctx, &userclient.SetUserMetaReq{
		UserId:   pointy.GetPointer(userId),
		MetaKey:  pointy.GetPointer(mqueuex.UserStatisticCollectEntryCount), // "_collect_entry_count"
		Incr:     pointy.GetPointer(int32(1)),
		UserMeta: userMeta,
	})

	return &types.CreateCollectResp{
		Status:  "ok",
		Message: "操作成功",
	}, nil
}
